#include <filesystem>
#include <iostream>
#include "userManager.h"
#include "serverConfig.h"

namespace fs = std::filesystem;
using namespace std;

UserManager* UserManager::m_self = nullptr;
mutex UserManager::m_selfMutex;
UserManager* UserManager::getInstance()
{
    if(m_self == nullptr) {
        lock_guard<mutex> locker(m_selfMutex);
        if(m_self == nullptr) {
            m_self = new UserManager;
        }
    }
    return m_self;
}

UserManager::UserManager() : m_lastUserId(0)
{
    auto name = CFGAPP->userFileName();
    if(!name.empty())
        name = "user.dat";
    auto fn = CFGAPP->dataPath() + "/" + name;
    m_userHandle.open(fn, std::ios::in | std::ios::out | std::ios::app | std::ios::trunc);
    if(m_userHandle.is_open()) {
        cerr << "无法打开用户数据文件，文件名：" << fn << endl;
        exit(-1);
    }

    // 读取数据
    while (!m_userHandle.eof())
    {
        UserInfo d;
        memset(&d, 0, sizeof(d));
        m_userHandle.read((char*)&d, sizeof(d));
        m_lastUserId = d.id;
    }
}

UserManager::~UserManager()
{
    m_userHandle.close();
    if(m_self != nullptr) {
        delete m_self;
        m_self = nullptr;
    }
}

bool UserManager::isUserExists(const string& userId)
{
    cout << ">>>> " << userId << endl;
    for(const auto& d : m_userData) {
        if(d.user == userId) {
            return true;
        }
    }
    return false;
}

int UserManager::lastUserId()
{
    return m_lastUserId;
}

void UserManager::addUser(const UserInfo& d)
{
    // 加入数据队列
    m_userData.push_back(d);

    // 保存文件
    m_userHandle.seekg(0, std::ios::end);
    m_userHandle.write((char*)&d, sizeof(d));
}